from model.user_message import UserMessage
from model.user import User
from model.job import Job
from model.company import Company
from sqlalchemy import desc

MESSAGE_TYPE = {
    1: '系统消息',
    2: '简历回执(投递简历，是否被人审核通过)',
    3: '发布工作-审核通过'
}


class UserMessageDao(object):
    def __init__(self, session):
        self.session = session

    def get_messages_by_user_id(self, user_id):
        q = self.session.query(UserMessage,
                               UserMessage.is_read,
                               Job.job_name,
                               UserMessage.message_id,
                               UserMessage.message_type,
                               UserMessage.message_date,
                               UserMessage.company_id,
                               Company.name,
                               UserMessage.user_id,
                               User.wx_nick_name,
                               User.header_img,
                               UserMessage.content
                               ) \
            .outerjoin(User, UserMessage.user_id == User.user_id) \
            .outerjoin(Job, UserMessage.job_id == Job.job_id) \
            .outerjoin(Company, UserMessage.company_id == Company.company_id) \
            .filter(UserMessage.user_id == user_id) \
            .order_by(desc(UserMessage.message_date)).all()
        list_d = []
        for f in q:
            list_d.append({
                "isRead": f.is_read,
                "job_name": f.job_name,
                "avatar": f.header_img,
                "message_id": f.message_id,
                "message_type": f.message_type,
                "message_date": f.message_date,
                "company_id": f.company_id,
                "company_name": f.name,
                "user_id": f.user_id,
                "user_name": f.wx_nick_name,
                "content": f.content
            })
        return list_d

    def update_read(self, message_id):
        msg = UserMessage()
        msg.message_id = message_id
        msg.is_read = 1
        self.session.merge(msg)
        self.session.commit()

    def get_send_by_job_id(self, job_id):
        q = self.session.query(UserMessage) \
            .filter(UserMessage.job_id == job_id).count()
        return q


if __name__ == '__main__':
    pass
